"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 多节点写入
Case Name   : 备机执行定义插件扩展的DDL语句
Create At   : 2023/07/19
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.备机执行加载扩展
    3.加载扩展后查询fdw，重复加载postgres_fdw扩展
    4.创建基于fdw的服务
    5.移动扩展对象到模式public
    6.扩展存在依赖，cascade删除
    7.查看日志
    8.清理环境
Expect      :
    1.成功
    2.成功，postgres_fdw，重复加载报错
    3.报错
    4.成功
    5.成功
    6.成功
    7.转发到主机执行，主机有写操作语句记录
    8.成功
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_node = Node('Standby1DbUser')
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.server = 'server_multi_node_write_0064'
        self.new_log_dir = os.path.join(macro.PG_LOG_PATH,
                                        'pg_log_multi_node_write0064')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc('reload',
                                               self.constant.GSGUC_SUCCESS_MSG,
                                               f'{self.log_statement}=all')
        self.assertTrue(result, f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.new_log_dir}'", single=True)
        self.assertTrue(result, f'执行失败:{step1}')
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', f'执行失败:{step1}')
        show_log_directory = self.common.show_param(self.log_directory)
        self.assertEquals(show_log_directory, self.new_log_dir, f'执行失败:{step1}')

        step2 = "-----step2:备机执行加载扩展;expect:成功-----"
        self.logger.info(step2)
        sql_msg = self.standby_sh.execut_db_sql(
            "create extension postgres_fdw;")
        self.logger.info(sql_msg)
        self.assertIn(self.constant.create_extension_success,
                      sql_msg, f'执行失败:{step2}')
        time.sleep(5)

        step3 = "-----step3:加载扩展后查询fdw，重复加载postgres_fdw扩展;expect:成功,重复加载报错-----"
        self.logger.info(step3)
        sql_msg = self.standby_sh.execut_db_sql(
            "select fdwname from pg_foreign_data_wrapper \
            where fdwname='postgres_fdw'; \
            create extension postgres_fdw;")
        self.logger.info(sql_msg)
        self.assertIn('postgres_fdw', sql_msg, f'执行失败:{step3}')
        self.assertIn('ERROR:  extension "postgres_fdw" already exists',
                      sql_msg, f'执行失败:{step3}')

        step4 = "-----step4:创建基于fdw的服务;expect:成功-----"
        self.logger.info(step4)
        sql_msg = self.standby_sh.execut_db_sql(
            f"create server {self.server} foreign data wrapper postgres_fdw;")
        self.logger.info(sql_msg)
        self.assertIn(self.constant.create_server_success,
                      sql_msg, f'执行失败:{step4}')

        step5 = "-----step5:移动扩展对象到模式public;expect:成功-----"
        self.logger.info(step5)
        sql_msg = self.standby_sh.execut_db_sql(
            "alter extension postgres_fdw set schema public;")
        self.logger.info(sql_msg)
        self.assertIn('ALTER EXTENSION', sql_msg, f'执行失败:{step5}')

        step6 = "-----step6:扩展存在依赖，cascade删除;expect:成功-----"
        self.logger.info(step6)
        sql_msg = self.standby_sh.execut_db_sql(
            "drop extension postgres_fdw cascade;")
        self.logger.info(sql_msg)
        self.assertIn(self.constant.drop_extension_success,
                      sql_msg, f'执行失败:{step6}')

        step7 = "-----step7:查看日志打印;expect:转发到主机执行，主机有写操作语句记录-----"
        self.logger.info(step7)
        shell_cmd = f"ls -t {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_dir, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"cat {logfile}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.logger.info(shell_msg)
        self.assertIn('we find new transfer request',
                      shell_msg, f'执行失败:{step7}')
        self.assertIn('Connecting to remote server',
                      shell_msg, f'执行失败:{step7}')
        self.assertIn(f'LOG:  libpqsw', shell_msg, f'执行失败:{step7}')

    def tearDown(self):
        step8 = "-----step8:恢复参数;expect:恢复参数成功-----"
        self.logger.info(step8)
        drop_res = self.standby_sh.execut_db_sql(
            'drop extension if exists postgres_fdw cascade;')
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.log_dir_default}'", single=True)
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_directory = self.common.show_param(self.log_directory)
        self.assertIn(self.constant.drop_extension_success,
                      drop_res, f'执行失败:{step8}')
        self.assertTrue(result1, f'执行失败:{step8}')
        self.assertTrue(restart_res, f'执行失败:{step8}')
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step8}')
        self.assertTrue(result2, f'执行失败:{step8}')
        self.assertTrue(result3, f'执行失败:{step8}')
        self.assertEquals(show_log_statement, self.log_statement_default,
                          f'执行失败:{step8}')
        self.assertEquals(show_log_directory, self.log_dir_default,
                          f'执行失败:{step8}')
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
